#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

pthread_mutex_t g_lock;
pthread_cond_t g_cond;
pthread_cond_t g_make_cond;

int g_bowl = 1;
void* Eatstart(void* arg)
{
    (void)arg;
    while(1)
    {
        pthread_mutex_lock(&g_lock);
        while(g_bowl<=0)
        {
            pthread_cond_wait(&g_cond,&g_lock);
        }
        g_bowl--;
        printf("i am %p,i eat %d\n",pthread_self(),g_bowl);
        pthread_mutex_unlock(&g_lock);
        pthread_cond_signal(&g_make_cond);
    }
    return NULL;
}

void* Makestart(void* arg)
{
    (void)arg;
    while(1)
    {
        pthread_mutex_lock(&g_lock);
        while(g_bowl>0)
        {
            pthread_cond_wait(&g_make_cond,&g_lock);
        }
        g_bowl++;
        printf("i am %p,i make %d\n",pthread_self(),g_bowl);
        pthread_mutex_unlock(&g_lock);
        pthread_cond_signal(&g_cond);
    }
    return NULL;
}
int main()
{
    //初始化
    pthread_mutex_init(&g_lock,NULL);
    pthread_cond_init(&g_cond,NULL);
    pthread_cond_init(&g_make_cond,NULL);
  
    pthread_t tid;
    int ret = pthread_create(&tid,NULL,Eatstart,NULL);
    if(ret < 0)
    {
        perror("create\n");
        return 0;
    }
    ret = pthread_create(&tid,NULL,Makestart,NULL);
    if(ret < 0)
    {
        perror("create\n");
        return 0;
    }
    while(1)
    {
        sleep(1);
    }
    //销毁锁
    pthread_cond_destroy(&g_cond);
    pthread_cond_destroy(&g_make_cond);
    pthread_mutex_destroy(&g_lock);


    return 0;
}
